package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService service;
    @PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart){
        log.info("购物车数据:{}",shoppingCart);
        Long dishId = shoppingCart.getDishId();
        Long currentId = BaseContext.getCurrentId();
        shoppingCart.setUserId(currentId);

        // 创建查询条件
        LambdaQueryWrapper<ShoppingCart> lam = new LambdaQueryWrapper<>();
        lam.eq(ShoppingCart::getUserId,currentId);
        if (dishId!=null){
            lam.eq(ShoppingCart::getDishId,dishId);
        }else {
            lam.eq(ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
        }
        // 查询当前菜品或者套餐是否在购物车中
        ShoppingCart cart1 = service.getOne(lam);
        if (cart1!=null){
            Integer num = cart1.getNumber();
            cart1.setNumber(num+1);
            service.updateById(cart1);
        }else {
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            service.save(shoppingCart);
            cart1 = shoppingCart;
        }
        return R.success(cart1);

    }
    @GetMapping("/list")
    public R<List<ShoppingCart>> list(){
        log.info("查看购物车...");
        LambdaQueryWrapper<ShoppingCart> lam = new LambdaQueryWrapper<>();
        lam.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
        lam.orderByAsc(ShoppingCart::getCreateTime);
        List<ShoppingCart> list = service.list(lam);
        return R.success(list);
    }
    @DeleteMapping("/clean")
    public R<String> clean(){
        LambdaQueryWrapper<ShoppingCart> lam = new LambdaQueryWrapper<>();
        lam.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());
        service.remove(lam);
        return R.success("购物车删除成功");
    }
}
